package run.siyuan.processor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import run.siyuan.util.MyHttpUtil;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

import java.util.List;

/**
 * {@code @className:} TbPageProcessor
 * {@code @Description:} TODO 京东 pageProcessor
 * {@code @author:} siyuan
 * {@code @date:} 2022/12/16 17:04
 */
@Slf4j
@Service
public class JDPageProcessor implements PageProcessor {

    private final Site site = Site.me()
            .setCharset("UTF-8")
            .setTimeOut(10000)
            .setRetrySleepTime(3000)
            // 设置请求头
            .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36")
            .setSleepTime(3);

    private static final String URL = "https://search.jd.com/Search?keyword=%E7%AC%94%E8%AE%B0%E6%9C%AC%E7%94%B5%E8%84%91&enc=utf-8";

    @Override
    public void process(Page page) {
        Selectable selectable = page.getHtml().css("div#J_goodsList");
        List<Selectable> list = page.getHtml().css("div#J_goodsList li").nodes();
        if (CollUtil.isEmpty(list)) {
            log.info("当前页没有商品信息");
            this.parsItemInfo(page);
            return;
        } else {
            for (Selectable itemSelect : list) {
                String itemUrl = itemSelect.css("div.p-name").links().toString();
                page.addTargetRequest(itemUrl);
                return;
            }
        }

    }

    private void parsItemInfo(Page page) {
        Html html = page.getHtml();
        // 商品详情地址
        String itemInfoUrl = page.getUrl().toString();
        // 商品图片
        List<Selectable> itemImages = html.css("div.spec-list li").nodes();
        for (Selectable itemImage : itemImages) {
            String itemImageUrl = itemImage.css("img", "src").toString();
            log.info("itemImageUrl:https:{}", itemImageUrl);
        }
        // 商品标题
        String itemName = html.css("div.sku-name", "text").toString();
        // sku
        // 规格
        List<Selectable> nodes = html.css("div#choose-attrs div.p-choose").nodes();

        for (Selectable node : nodes) {
            List<Selectable> skuItems = node.css("div.item").nodes();
            for (Selectable skuItem : skuItems) {
                String dataSku = "";
                if (ObjectUtil.isNotEmpty(skuItem.css("div.selected", "data-sku").toString())) {
                    dataSku = skuItem.css("div.selected", "data-sku").toString();
                    String dataValue = skuItem.css("div.selected", "data-value").toString();
                    String title = skuItem.css("div.selected i", "text").toString();

                    String priceUrl = "https://item-soa.jd.com/getWareBusiness?skuId=";
                    String priceResult = MyHttpUtil.reqGet(priceUrl + dataSku);
                    JSONObject price = JSONUtil.parseObj(priceResult).getJSONObject("price");

                    log.info("dataSku:{},dataValue:{},dataTitle:{},price:{}", dataSku, dataValue, title, price);
                } else {
                    dataSku = skuItem.css("div.item", "data-sku").toString();
                    String itemDetailUrl = "https://item.jd.com/{}.html";
                    String skuUrl = StrUtil.format(itemDetailUrl, dataSku);
                    page.addTargetRequest(skuUrl);
                }


            }
        }


    }

    @Override
    public Site getSite() {
        return this.site;
    }

    public static void main(String[] args) {
        Spider.create(new JDPageProcessor())
                .addUrl(URL)
                .run();
        ;
    }

}
